﻿package net.wangit.dev.chart;

import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.dev.LockUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;

public class ChartUI implements UnitInterceptor {

	public static final String KEY = "net.wangit.dev.chart.ChartUI.chartId";
	private static final String SQL = "select * from CHART where cid=?";

	public ChartUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String domain = ConsoleDomainUtil.getDomain(ac);
		String source = ac.getRequestParameter("src");
		boolean copy = !Checker.isEmpty(source);
		String chartId = copy ? source : ActionContextHelper
				.getRequest2Session(ac, "chartid",
						ChartUI.KEY, null);
		Unit chartUnit = (Unit) unit.getElement("chart").getObject();
		String unitShowMode = chartUnit.getShowMode();
		if ("a".equals(unitShowMode))
			unit.removeElement("preview");
		else
			unit.getElement("preview").setLink(
					(new StringBuilder("/chart?domain=")).append(domain)
							.append("&chartid=").append(chartId).toString());
		if (!copy && "a".equals(unitShowMode)) {
			String groupId = ac.getRequestParameter("groupid");
			chartUnit.getElement("gid").setDefaultValue(groupId);
		} else if (chartUnit.getData() == null) {
			DB db = DBHelper.getDomainDB(domain);
			MapList data = db.query(ChartUI.SQL, chartId,
					2);
			chartUnit.setData(data);
			if (copy) {
				data.put(0, "cid", "");
				data.put(0, "l", "0");
			}
		}
		LockUtil.setElements(ac, chartUnit, new Object[][] { new Object[] {
				chartUnit, "save" } });
		return unit.write(ac);
	}
}
